package com.changdu.seatunnel.admin.handlers;

import com.changdu.seatunnel.admin.config.SeatunnelQueryProperty.DingRobotConfig;
import com.changdu.seatunnel.admin.entity.SyncTask;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;

import lombok.extern.slf4j.Slf4j;

/**
 * 钉钉消息
 */
@Slf4j
public class DingRobotHandler {

    private final DingRobotConfig dingRobot;
    private final DingTalkClient client;
    
    public DingRobotHandler(DingRobotConfig dingRobot) {
    	this.dingRobot = dingRobot;
    	this.client = new DefaultDingTalkClient(dingRobot.getUrl());
    }
    
    /**
     * 发送钉钉消息
     * @param content
     * @param messageType
     * @return
     */
    public void sendDingTalkMessage(SyncTask syncTask, String lag) {
    	String content = String.format(dingRobot.getContent(), syncTask.getDomain(), syncTask.getId(), syncTask.getShowName(), syncTask.getStatus().describeConstable(), lag);
        try {
            OapiRobotSendRequest request = new OapiRobotSendRequest();
            OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
            markdown.setTitle(dingRobot.getTitle());
            markdown.setText(content);
            request.setMsgtype("markdown");
            request.setMarkdown(markdown);
            client.execute(request);
        } catch (Exception e) {
            log.error("钉钉消息发送失败：message: {}, error: {}", e.getMessage(), e);
        }
    }
    
}
